﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FileDFS.Model;
using System.IO;
using FileDFS.Utils;
using FileDFS.Utils.PathConfig;

namespace FileDFS.Bll
{
    /*
     * Coder:Tieria
     * WriteTime:2015.5.13
     * FileName:FileExtensionEnum.cs
     * ReMark:文件类型枚举,因为限制,只能上传几种类型,不在此范围的将不能上传
     */
    public class FileHandler
    {
        public static FileHandler GetInstance()
        {
            return new FileHandler();
        }

        #region 保存每一个文件
        /// <summary>
        /// 保存每个上传的文件
        /// </summary>
        /// <param name="uploadModel"></param>
        /// <returns></returns>
        public FileResultBody SaveFile(FileUploadModel uploadModel)
        {
            FileResultBody resultBody = new FileResultBody()
            {
                Id = uploadModel.Id
            };
          // MemoryStream stream = new MemoryStream(uploadModel.DataSource, 0, uploadModel.DataSource.Length);
          //  Stream stream = uploadModel.DataSource;   
            string fileName = AlgorithmHelper.GetGuid() + "." + uploadModel.FileExtension.ToString();
            //当前虚拟路径和绝对路径
          PathDetail currentPath = Utils.PathConfig.CatalogHandler.GetInstance().GetCurrentPath(OptionGetEnum.FilePrivate);
                //Utils.PathConfig.ConfigHandler.GetPath();
            //虚拟路径
          resultBody.FileFullPath = PathHelper.CombineRelativePath(currentPath.Virtual_FullPath, fileName);

            //保存的文件路径
            //uploadDetail.FilePath = relativePath;
            //文件写入流
           // Stream stream = uploadModel.DataSource;
            using (FileStream fw = File.OpenWrite(Path.Combine(currentPath.Absolute_FullPath, fileName)))
            {
                byte[] buffers = new byte[1024 * 1024 * 3];
                int r = uploadModel.DataSource.Read(buffers, 0, buffers.Length);
                while (r > 0)
                {
                    fw.Write(buffers, 0, r);
                    r = uploadModel.DataSource.Read(buffers, 0, buffers.Length);
                }
            }
            //stream.Close();
            return resultBody;
        }
        #endregion


        #region 是否为大文件
        public bool IsLargeFile(byte[] dataSource)
        {
            if (dataSource.Length > (1024 * 1024 * 10))
            {
                return true;
            }
            return false;
        }
        #endregion


    }
}
